package cn.wolfcode.shop.server.service.impl;

import cn.wolfcode.shop.api.domain.User;
import cn.wolfcode.shop.api.service.IUserService;
import cn.wolfcode.shop.server.mapper.UserMapper;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class UserServiceImpl implements IUserService {

    public static Map<String,Object> userCache = new ConcurrentHashMap<>();

    @Autowired
    private UserMapper userMapper;

    @Override
    public User register(User user) {
        if (isExist(user.getUserName())) {
            throw new RuntimeException("该用户名已存在");
        }
        user.setNickName(user.getUserName());
        userMapper.insert(user);
        return user;
    }

    @Override
    public String login(String username, String password) {
        if (!isExist(username)) {
            throw new RuntimeException("该用户不存在");
        }
        User user = userMapper.selectByInfo(username, password);
        if (user == null){
            throw new RuntimeException("密码输入错误");
        }
        return creatToken(user);
    }

    @Override
    public Boolean logout(String token) {
        Object remove = userCache.remove(token);
        if (remove==null){
            throw new RuntimeException("用户未登录");
        }
        return true;
    }

    @Override
    public Boolean isExist(String username) {
        return userMapper.isExist(username);
    }

    @Override
    public String creatToken(User user) {
        String token = UUID.randomUUID().toString();
        userCache.put(token,user);
        return token;
    }
}
